package pumpkin.ast;

import pumpkin.evt.Environment;
import pumpkin.word.SymbolTxt;
import pumpkin.word.Token;
import pumpkin.word.TokenSource;
import pumpkin.word.TokenType;

/**
 * * T'->*FT'|e
 * 
 * @author jiang
 *
 */
public class Texprp implements Node {
	private Fexpr fexpr =null;
	private Texprp texprp = null;
	private char symbol = 0;
	Epsilon epsilon =null;
	boolean useEpsilon = false;

	public char getOerator() {
		return symbol;
	}

	@Override
	public void build(TokenSource tokenSource) {
		Token t = tokenSource.next();
		if (t.getType() == TokenType.SYMBOL) {
			if (SymbolTxt.Multi.getSymbol().equals(t.getText())) {
				symbol = '*';
				useEpsilon = false;
			} else if (SymbolTxt.Div.getSymbol().equals(t.getText())) {
				symbol = '/';
				useEpsilon = false;
			} else {
				useEpsilon = true;
				epsilon=new Epsilon();
				tokenSource.pushBack(t);
			}
		} else {
			useEpsilon = true;
			epsilon=new Epsilon();
			tokenSource.pushBack(t);
		}
		if (!useEpsilon) {
			fexpr = new Fexpr();
			texprp = new Texprp();
			fexpr.build(tokenSource);
			texprp.build(tokenSource);
		}
	}

	@Override
	public Object excute(Environment env) {
		if(useEpsilon) {
			return null;
		}
		Object left = fexpr.excute(env);
		Object right = texprp.excute(env);
		if (left == null) {
			return right;
		}
		if (right == null) {
			return left;
		}
		char c = texprp.getOerator();
		if (c == '*') {
			if (left instanceof Double || right instanceof Double) {
				return (Double.parseDouble(left.toString()) * Double.parseDouble(right.toString()));
			} else {
				return (Integer.parseInt(left.toString()) * Integer.parseInt(right.toString()));
			}
		} else if (c == '/') {
			if (left instanceof Double || right instanceof Double) {
				return (Double.parseDouble(left.toString()) / Double.parseDouble(right.toString()));
			} else {
				return (Integer.parseInt(left.toString()) / Integer.parseInt(right.toString()));
			}
		}
		return null;
	}
}
